<?php
namespace Admin\Controller;

class OrderController extends CommonController
{

    /**
     * 列表
     *
     * @param  void
     * @return void
     */
    public function index()
    {
        if (IS_POST) {
            $this->delete();
        } else {
            $get = I('get.');
            $where = array();
            if (! empty($get['keyword'])) {
                $where['c.reciver_phone|o.order_sn'] = array( 'like', "%{$get['keyword']}%" );
            }
            if (! empty($get['nickname'])) {
                $where['m.nickname|m.openid'] = array( 'like', "%{$get['nickname']}%" );
            }

            if (! empty($get['start_create_time'])) {
                $where['o.create_time'] = array( 'egt' , strtotime("{$get['start_create_time']} 00:00:00") );
            }
            if (! empty($get['end_create_time'])) {
                $where['o.create_time'] = array( 'elt' , strtotime("{$get['end_create_time']} 23:59:59") );
            }

            if (! empty($get['start_create_time']) && ! empty($get['end_create_time'])){
                $where['o.create_time'] = array('between', array(strtotime("{$get['start_create_time']} 00:00:00"), strtotime("{$get['end_create_time']} 23:59:59")));
            }

            if (isset($get['pay_state']) && $get['pay_state'] ==! '') {
                $where['o.pay_state'] = $get['pay_state'];
            }
            if (! empty($get['region_id'])) {
                $where['c.region_id'] = $get['region_id'];
            }

            $model = M()->table('__ORDER__ AS o')->join('LEFT JOIN __MEMBER__ AS m ON o.member_id = m.member_id')->join( 'RIGHT JOIN __ORDER_COMMON__ AS c ON o.order_id = c.order_id' );
            $field = 'o.order_id,o.order_sn,o.store_id,o.member_id,m.openid,m.channel,m.nickname,m.order_count,o.create_time,o.order_amount,o.order_state,o.pay_state,o.coupon_id,o.pay_id,c.reciver_name,c.region_id,c.region_name,c.reciver_phone,c.address';
            $list = $this->lists($model, $field, $where, 'o.order_id DESC', 20);
            $coupon = getCouponList(false);
            $this->assign('coupon', $coupon);
            $channel = getChannel(false);
            $this->assign('channel', $channel);
            $region = getRegion(false);
            $exportUrl = U('admin/order/exportExcel', $get);
            $this->assign('export_url', $exportUrl);

            $this->assign('region', $region);
            $this->assign('list', $list);
            $this->assign('get', $get);
            $this->display();
        }
    }

    public function exportExcel()
    {
        $get = I('get.');
        $where = array();
        if (! empty($get['keyword'])) {
            $where['c.reciver_phone|o.order_sn'] = array( 'like', "%{$get['keyword']}%" );
        }
        if (! empty($get['nickname'])) {
            $where['m.nickname|m.openid'] = array( 'like', "%{$get['nickname']}%" );
        }

        if (! empty($get['start_create_time'])) {
            $where['o.create_time'] = array( 'egt' , strtotime("{$get['start_create_time']} 00:00:00") );
        }
        if (! empty($get['end_create_time'])) {
            $where['o.create_time'] = array( 'elt' , strtotime("{$get['end_create_time']} 23:59:59") );
        }

        if (! empty($get['start_create_time']) && ! empty($get['end_create_time'])){
            $where['o.create_time'] = array('between', array(strtotime("{$get['start_create_time']} 00:00:00"), strtotime("{$get['end_create_time']} 23:59:59")));
        }

        if (isset($get['pay_state']) && $get['pay_state'] =! '') {
            $where['o.pay_state'] = $get['pay_state'];
        }
        if (! empty($get['region_id'])) {
            $where['c.region_id'] = $get['region_id'];
        }

        $channel = getChannel(false);
        $field = 'o.order_id,o.order_sn,o.member_id,m.openid,m.channel,m.nickname,m.order_count,o.create_time,o.order_amount,o.pay_state,o.pay_id,c.reciver_name,c.region_id,c.region_name,c.reciver_phone,c.address';
        $list = M()->table('__ORDER__ AS o')->join('LEFT JOIN __MEMBER__ AS m ON o.member_id = m.member_id')->join( 'RIGHT JOIN __ORDER_COMMON__ AS c ON o.order_id = c.order_id' )->field($field)->where($where)->order('o.order_id DESC')->select();
        $excelData = array();
        foreach ($list as $key => $val){
            $val['pay_state'] = $val['pay_state'] == 1 ? '已支付' : '未支付';
            $val['create_time'] = time_format($val['create_time']);
            $val['channel'] = str_replace('qrscene_', '', $val['channel']);
            $val['channel'] = $channel[$val['channel']];
            unset($val['pay_id']);
            unset($val['region_id']);
            $excelData[$val['order_id']] = $val;

        }

        $title = array(
            "order_id" => "订单ID",
            "order_sn" => "订单编号",
            "member_id" => "会员ID",
            "openid" => "OPENID",
            "channel" => "渠道",
            "nickname" => "会员昵称",
            "order_count" => "购买次数",
            "create_time" => "下单时间",
            "order_amount" => "金额",
            "pay_state" => "支付状态",
            "reciver_name" => "收货人",
            "region_name" => "楼宇",
            "reciver_phone" => "电话",
            "address" => "详细地址",
        );
        exportExcel($excelData, $title, 'export_order_' . date('YmdHis'));
        exit();

    }

    public function importMemberOrderCount()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $total = 200000;
        $limit = 50;
        if ($id <= $total) {
            $offset = $id + $limit;
            $list = M('Member')->field('member_id,openid')->where("member_id > {$id} AND member_id <= {$offset}")->select();
            if (empty($list)) {
                $id = $offset;
            } else {
                 foreach ($list as $key => $val) {

                    $id = $val['member_id'];
                    $where = array('member_id' => $val['member_id'], 'pay_state' => 1);
                    $count = M('Order')->where($where)->count();
                    M('Member')->where('member_id = ' . $val['member_id'])->save(array('order_count' => $count));
                    echo 'user_id = ' . $val['member_id'] . '|';
                    echo 'true<br>' . PHP_EOL;
                }
            }
            $url = "?id=" . $id;
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$url'";
            echo "</script>";
        } else {
            echo "ok";
        }
    }
    
    /**
     * 查看
     *
     * @param void
     * @return void
     */
    public function view()
    {
        $id = I('get.id');
        if (empty($id)) {
            $this->error('无效的数据');
        }
        $info = M('Order')->where('order_id = ' . $id)->find();
        $common = M('OrderCommon')->where('order_id = ' . $id)->find();
        $goods = M('OrderGoods')->where('order_id = ' . $id)->select();

        $store = getStoreList();
        $region = M('Region')->where(array('region_id' => $common['region_id']))->find();
        $member = M('Member')->where(array('member_id' => $info['member_id']))->find();
        $this->assign('region', $region);
        $this->assign('member', $member);
        $this->assign('info', $info);
        $this->assign('common', $common);
        $this->assign('goods', $goods);
        $this->assign('store', $store);

        $this->display();
    }

    /**
     * 修改
     *
     * @param void
     * @return void
     */
    public function edit()
    {
        if (IS_POST) {
            $data = I('post.');
            $result = D('OrderGoods')->update($data);
            if ($result) {
                $this->success('保存成功', U('admin/order/send'));
            } else {
                $this->error('保存失败');
            }
        } else {
            $id = I('get.id');
            if (empty($id)) {
                $this->error('无效的数据');
            }
            $goods = M('OrderGoods')->where('id = ' . $id)->find();
            if (empty($goods)) {
                $this->error('无效的数据');
            }
            $info = M('order')->where('order_id = ' . $goods['order_id'])->find();
            $store = getStore($goods['store_id']);
            $area = getArea();
            $this->assign('store', $store);
            $this->assign('area', $area);
            $this->assign('goods', $goods);
            $this->assign('info', $info);
            $this->display();
        }
    }

    /**
     * 删除
     *
     * @param void
     * @return void
     */
    public function changeState()
    {
        $id = array_unique((array) I('id', 0));
        $state = I('order_state', 0);
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        if ($state == ''){
            $this->error('请选择要变更的状态!');
        }
        $where = array( 'id' => array( 'in', $id ) );
        $data = array( 'order_state' => $state, 'update_time' => time() );
        $result = M('OrderGoods')->where($where)->save($data);
        if ($result) {
            $this->success('变更成功');
        } else {
            $this->error('变更失败');
        }
    }

    /**
     * 删除
     *
     * @param void
     * @return void
     */
    public function delete()
    {
        $id = array_unique((array) I('id', 0));
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $where = array( 'order_id' => array( 'in', $id ) );
        $data = array( 'order_state' => 0, 'update_time' => time() );
        $result = M('Order')->where($where)->save($data);
        if ($result) {
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }
    }


    public function send()
    {
        $get = I('get.');
        $where = array();
        if (! empty($get['keyword'])) {
            $where['c.reciver_phone|g.order_sn'] = array( 'like', "%{$get['keyword']}%" );
        }
        if (! empty($get['nickname'])) {
            $where['m.nickname|m.openid'] = array( 'like', "%{$get['nickname']}%" );
        }

        if (! empty($get['store_id'])) {
            $where['g.store_id'] = $get['store_id'];
        }
        if (isset($get['order_state']) && $get['order_state'] != '') {
            $where['g.order_state'] = $get['order_state'];
        }

        if (! empty($get['start_create_time'])) {
            $where['g.menu_date'] = array( 'egt' , strtotime("{$get['start_create_time']}") );
        }
        if (! empty($get['end_create_time'])) {
            $where['g.menu_date'] = array( 'elt' , strtotime("{$get['end_create_time']}") );
        }

        if (! empty($get['start_create_time']) && ! empty($get['end_create_time'])){
            $where['g.menu_date'] = array('between', array(strtotime("{$get['start_create_time']}"), strtotime("{$get['end_create_time']}")));
        }

        if (isset($get['pay_state']) && $get['pay_state'] ==! '') {
            $where['o.pay_state'] = $get['pay_state'];
        }
        if (! empty($get['region_id'])) {
            $where['c.region_id'] = $get['region_id'];
        }
        $where['o.pay_state'] = 1;
        $model = M()->table('__ORDER_GOODS__ AS g')
            ->join('LEFT JOIN __ORDER__ AS o ON g.order_id = o.order_id')
            ->join('LEFT JOIN __MEMBER__ AS m ON g.member_id = m.member_id')
            ->join('LEFT JOIN __ORDER_COMMON__ AS c ON g.order_id = c.order_id');
        $field = 'g.id,g.area_id,g.menu_date,g.menu_id,g.order_id,g.order_sn,g.store_id,g.member_id,g.goods_name,g.goods_num,m.openid,m.nickname,m.order_count,o.create_time,o.order_amount,g.order_state,o.pay_state,c.reciver_name,c.region_id,c.region_name,c.reciver_phone,c.address';
        $list = $this->lists($model, $field, $where, 'g.id DESC', 20);

        $area = getArea(false);
        $store = getStoreList(false);
        $region = getRegion(false);
        $exportUrl = U('admin/order/exportSend', $get);
        $this->assign('export_url', $exportUrl);
        $this->assign('area', $area);
        $this->assign('store', $store);
        $this->assign('region', $region);
        $this->assign('list', $list);
        $this->assign('get', $get);
        $this->display();
    }

    public function exportSend()
    {
        $get = I('get.');
        $where = array();
        if (! empty($get['keyword'])) {
            $where['c.reciver_phone|g.order_sn'] = array( 'like', "%{$get['keyword']}%" );
        }
        if (! empty($get['nickname'])) {
            $where['m.nickname|m.openid'] = array( 'like', "%{$get['nickname']}%" );
        }

        if (! empty($get['store_id'])) {
            $where['g.store_id'] = $get['store_id'];
        }
        if (isset($get['order_state']) && $get['order_state'] != '') {
            $where['g.order_state'] = $get['order_state'];
        }

        if (! empty($get['start_create_time'])) {
            $where['g.menu_date'] = array( 'egt' , strtotime("{$get['start_create_time']}") );
        }
        if (! empty($get['end_create_time'])) {
            $where['g.menu_date'] = array( 'elt' , strtotime("{$get['end_create_time']}") );
        }

        if (! empty($get['start_create_time']) && ! empty($get['end_create_time'])){
            $where['g.menu_date'] = array('between', array(strtotime("{$get['start_create_time']}"), strtotime("{$get['end_create_time']}")));
        }

        if (isset($get['pay_state']) && $get['pay_state'] ==! '') {
            $where['o.pay_state'] = $get['pay_state'];
        }
        if (! empty($get['region_id'])) {
            $where['c.region_id'] = $get['region_id'];
        }
        $where['o.pay_state'] = 1;
        $model = M()->table('__ORDER_GOODS__ AS g')
            ->join('LEFT JOIN __ORDER__ AS o ON g.order_id = o.order_id')
            ->join('LEFT JOIN __MEMBER__ AS m ON g.member_id = m.member_id')
            ->join('LEFT JOIN __ORDER_COMMON__ AS c ON g.order_id = c.order_id');
        $field = 'g.id,g.area_id,g.menu_date,g.menu_id,g.order_id,g.order_sn,g.store_id,g.member_id,g.goods_name,g.goods_num,m.openid,m.nickname,m.order_count,o.create_time,o.order_amount,g.order_state,o.pay_state,c.reciver_name,c.region_id,c.region_name,c.reciver_phone,c.address';
        $list = $model->where($where)->field($field)->order('g.id DESC')->select();
        $area = getArea(false);
        $store = getStoreList(false);

        $excelData = array();
        foreach ($list as $key => $val){
            $val['menu_date'] = date('Y-m-d', $val['menu_date']);
            $val['pay_state'] = $val['pay_state'] == 1 ? '已支付' : '未支付';
            $val['create_time'] = time_format($val['create_time']);
            $val['area_id'] = $area[$val['area_id']];
            $val['store_id'] = $store[$val['store_id']];
            $val['order_state'] = getOrderState($val['order_state']);
            $excelData[$val['id']] = $val;

        }
        $title = array(
            "id" => "ID",
            "area_id" => "区域",
            "menu_date" => "菜单日期",
            "menu_id" => "菜单ID",
            "order_id" => "订单ID",
            "order_sn" => "订单编号",
            "store_id" => "商户",
            "member_id" => "会员ID",
            "goods_name" => "菜品名称",
            "goods_num" => "菜品数量",
            "openid" => "微信ID",
            "nickname" => "昵称",
            "order_count" => "下单次数",
            "create_time" => "下单时间",
            "order_amount" => "订单总金额",
            "order_state" => "订单状态",
            "pay_state" => "支付状态",
            "reciver_name" => "收货人姓名",
            "region_id" => "楼宇ID",
            "region_name" => "楼宇",
            "reciver_phone" => "收货人电话",
            "address" => "详细地址",
        );
        exportExcel($excelData, $title, 'export_order_' . date('YmdHis'));
        exit();
    }
}